import {html} from 'htm/preact';
import {isTextFieldEntryEdited, TextFieldEntry} from "@bpmn-io/properties-panel";
import {useService} from "bpmn-js-properties-panel";
import {getMultiInstance, updateMultiInstance} from "@/components/activiti/util";
import {getBusinessObject} from "bpmn-js/lib/util/ModelUtil";

const component = {
  id: 'elementVariable',
  component: ElementVariable,
  isEdited: isTextFieldEntryEdited
}

if(window['register']) {
  window['register'].regComponent(component.id,component)
}
export default function(element) {
  component['element']=element;
  return component;
}

function ElementVariable(props) {
  let { element, id } = props;

  const modeling = useService('modeling');
  const translate = useService('translate');
  const debounce = useService('debounceInput');
  const bpmnFactory = useService('bpmnFactory');
  const commandStack = useService('commandStack');

  const businessObject = getBusinessObject(element);
  let loopCharacteristics = businessObject.get('loopCharacteristics');
  const getValue = () => {
    if(loopCharacteristics&&loopCharacteristics.$attrs){
      return loopCharacteristics.$attrs['activiti:elementVariable'] || '';
    }
    return '';
  }

  const setValue = value => {
    return updateMultiInstance(element,businessObject,bpmnFactory,commandStack,{
      'activiti:elementVariable': value,
      'activiti:elementIndexVariable': value+"Index"
    })
  }

  return html`<${TextFieldEntry}
    id=${ id }
    element=${ element }
    label=${ translate('ElementVariable') }
    getValue=${ getValue }
    setValue=${ setValue }
    debounce=${ debounce }
  />`
}
